package db;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

@SuppressWarnings("deprecation")
public class DBManager {

	private Session session;
	private TagManager tagManager;



	public DBManager() {
		SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
		this.session = sessionFactory.openSession();
		tagManager = new TagManager(this.session);
	}
	

	
	public String[] getFilesByTag(String tag){
		Query query = session.createQuery("select distinct file from Tag where tag='"+tag+"'");
		@SuppressWarnings("unchecked")
		List<String> temp = query.list();
		if(temp.isEmpty())
			return null;//no tags
		String[] files = new String[temp.size()];
		Iterator<String> getf= temp.iterator();
		for(int i = 0;i < temp.size();i++){
			files[i] = getf.next();
		}
		return files;
	}
	
	
	public boolean addTag(Tag t){
		tagManager.saveTag(t);
		session.flush();
		return true;		
	}
	
	public boolean removeFile(String file){
		Query query = session.createQuery("from Tag where file='"+file+"'");
		@SuppressWarnings("unchecked")
		List<Tag> files = query.list();
		Iterator<Tag> getTag = files.iterator();
		while (getTag.hasNext()){
			Tag t = getTag.next();
			tagManager.deleteTag(t);
		}
		session.flush();
		return true;		
	}

		public String[] getAllTags(){
			Query query = session.createQuery("select distinct tag from Tag");
			@SuppressWarnings("unchecked")
			List<String> temp = query.list();
		//	Iterator<String> getTag = tags.iterator();
			String[] tags = new String[temp.size()];
			Iterator<String> getTag= temp.iterator();
			for(int i = 0;i < temp.size();i++){
				tags[i] = getTag.next(); 
			}
			
			return tags;
		}
	
	
	
	
	
	
}
